package com.fsj.spring.web;

import Model.Student;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fsj.spring.model.TUser;
import com.fsj.spring.service.IDeptService;
import com.fsj.spring.service.IUserService;
import com.fsj.spring.util.DataGridModel;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.pclong.commons.http.HttpHelper;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;
import com.pclong.commons.http.HttpHelper;
        
@Controller
@RequestMapping("/user")
public class UserController {

    public UserController()
    {
    
    }
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model) throws Exception {
        model.addAttribute("deptList", deptService.getDeptList());
        return "user/list";
    }

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public void Test(HttpServletRequest req, HttpServletResponse res) throws Exception {
        res.setContentType("text/html;charset=UTF-8");
        PrintWriter out = res.getWriter();
        try {
            /* TODO output your page here*/
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet RequestInfo</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet RequestInfo at " + req.getContextPath() + "</h1>");
            out.println("thanks , my god. bless everywhere!..haha. "+HttpHelper.Get());
            out.println("</body>");
            out.println("</html>");

        } finally {
            out.close();
        }
    }

    @RequestMapping(value = "/to.aspx", method = RequestMethod.GET)
    public void To(HttpServletRequest req, HttpServletResponse res) throws Exception {
        req.getRequestDispatcher("/user/xml").forward(req, res);
    }

    @RequestMapping(value = "/xml", method = RequestMethod.GET)
    public void Xml(HttpServletRequest req, HttpServletResponse res) throws Exception {
        res.setContentType("text/xml;charset=UTF-8");
        PrintWriter out = res.getWriter();
        try {
            /* TODO output your page here*/
            out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            out.println("<Result value=\"true\" message=\"Success!\" />");
//            out.println("	<tx:advice id=\"txAdvice\" transaction-manager=\"txManager\"> "
//                    + " <tx:attributes> "
//                    + " <tx:method name=\"get*\" read-only=\"true\"/>"
//                    + "<tx:method name=\"query*\" read-only=\"true\"/>"
//                    + "<tx:method name=\"find*\" read-only=\"true\"/>"
//                    + "<tx:method name=\"load*\" read-only=\"true\"/>"
//                    + "<tx:method name=\"*\" rollback-for=\"Exception\"/>"
//                    + "</tx:attributes>"
//                    + "</tx:advice>");

        } finally {
            out.close();
        }
    }

    @RequestMapping(value = "/student", method = RequestMethod.GET)
    @ResponseBody
    public Student Student(HttpServletRequest req, HttpServletResponse res) throws Exception {

//        ("text/xml;charset=UTF-8")
//        ("application/json;charset=UTF-8"
        ModelAndView mv = new ModelAndView();
        res.setContentType("text/json");
        Student stu = new Student();
        stu.setName("pcl");
        stu.setSex("pcl");
        stu.setId(Long.parseLong("1"));
        return stu;

    }

    @RequestMapping(value = "/json", method = RequestMethod.GET)
    public Map<String, Object> TestJson(HttpServletRequest req, HttpServletResponse res, Model mode) throws Exception {
//        ("text/xml;charset=UTF-8")
//        ("application/json;charset=UTF-8"
        System.out.println("###############0##TestJson##################");
//        ModelAndView mav = new ModelAndView("jsonView");
        // Map<String, Object>  map=(Map<String, Object>) new ArrayList<Map<String,Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        Student stu = new Student();
        stu.setName("pcl");
        stu.setSex("pcl");
        stu.setId(Long.parseLong("1"));
        mode.addAttribute("name", "mylove");
        map.put("student", stu);
        return map;

    }

    @RequestMapping(value = "/testlist", method = RequestMethod.GET)
    public List<Map<String, Object>> TestList(HttpServletRequest req, HttpServletResponse res, Model mode) throws Exception {
//        ("text/xml;charset=UTF-8")
//        ("application/json;charset=UTF-8"
        System.out.println("###############0##TestJson##################");
//        ModelAndView mav = new ModelAndView("jsonView");
        // Map<String, Object>  map=(Map<String, Object>) new ArrayList<Map<String,Object>>();        
        List<Map<String, Object>> students = new ArrayList<Map<String, Object>>();
        Map<String, Object> s1 = new HashMap<String, Object>();
        s1.put("name", "jim");
        s1.put("age", "15");
        students.add(s1);
        Map<String, Object> s2 = new HashMap<String, Object>();
        s2.put("name", "lucy");
        s2.put("age", "12");
        students.add(s2);
        return students;

    }

    @RequestMapping(value = "/googlejson", method = RequestMethod.GET)
    public void googlejson(HttpServletRequest req, HttpServletResponse res) throws Exception {
        res.setContentType("text/xml;charset=UTF-8");
        PrintWriter out = res.getWriter();
        try {
            //DataObject obj = new DataObject();
            // Gson gson = new Gson();
            Student stu = new Student();
            stu.setName("pcl");
            stu.setSex("pcl");
            stu.setId(Long.parseLong("1"));
            Gson gson = new GsonBuilder().setPrettyPrinting().create();

            String json = gson.toJson(stu);
            out.println(json);
//            User user = new User();
//            ObjectMapper mapper = new ObjectMapper();
//
//            try {
//
//                // convert user object to json string, and save to a file
//                mapper.writeValue(new File("c:\\user.json"), user);
//
//                // display to console
//                System.out.println(mapper.writeValueAsString(user));
//
//            } catch (JsonGenerationException e) {
//
//                e.printStackTrace();
//
//            } catch (JsonMappingException e) {
//
//                e.printStackTrace();
//
//            } catch (IOException e) {
//
//                e.printStackTrace();
//
//            } {"age":29,"messages":["msg 1","msg 2","msg 3"],"name":"mkyong"}
            // System.out.println(mapper.defaultPrettyPrintingWriter().writeValueAsString(user));
//                {
//  "age" : 29,
//  "messages" : [ "msg 1", "msg 2", "msg 3" ],
//  "name" : "mkyong"
//}
            
        } finally {
            out.close();
        }


    }

    @RequestMapping(value = "/getjson", method = RequestMethod.GET)
    protected void getJsonDataExample(HttpServletResponse response) {

        MappingJacksonHttpMessageConverter jsonConverter = new MappingJacksonHttpMessageConverter();

        MediaType jsonMimeType = MediaType.APPLICATION_JSON;

        Object jsonBean = new String("mock for the json object which have to be replaced with real one");
        Student stu = new Student();
        stu.setName("pcl");
        stu.setSex("pcl");
        stu.setId(Long.parseLong("1"));

        if (jsonConverter.canWrite(stu.getClass(), jsonMimeType)) {

            try {

                jsonConverter.write(stu, jsonMimeType, new ServletServerHttpResponse(response));

            } catch (IOException m_Ioe) {
            } catch (HttpMessageNotWritableException p_Nwe) {
            }

        }

    }

    @RequestMapping(value = "/queryList", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryList(DataGridModel dgm, TUser user) throws Exception {
        //spring太给力了，可以自动装配两个对象  会自动的装返回的Map转换成JSON对象
        //return userService.getPageListByExemple(dgm, user); 
        return userService.getPageList(dgm, user);
    }

    @RequestMapping(value = "/popWindow", method = RequestMethod.GET)
    public String popWindow() throws Exception {
        return "user/popWindow";
    }

    @RequestMapping(value = "/addOrUpdate", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> addOrUpdate(TUser user) throws Exception {
        //spring会利用jackson自动将返回值封装成JSON对象，比struts2方便了很多
        Map<String, String> map = new HashMap<String, String>();
        try {
            userService.addOrUpdate(user);
            map.put("mes", "操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("mes", "操作失败");
            throw e;
        }
        return map;
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> delete(@RequestParam("uid") List<Integer> uid) throws Exception {
        //spring mvc 还可以将参数绑定为list类型
        Map<String, String> map = new HashMap<String, String>();
        try {
            userService.deleteUsers(uid);
            map.put("mes", "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("mes", "删除失败");
            throw e;
        }
        return map;//重定向
    }
    private IDeptService deptService;

    public IDeptService getDeptService() {
        return deptService;
    }

    public void setDeptService(IDeptService deptService) {
        this.deptService = deptService;
    }
//    @Autowired(required=true)
//     @Qualifier("userService")
//     @Resource(name="userService")
//    @Autowired
//    @Qualifier
    @Resource
    public IUserService userService;

    public IUserService getUserService() {
        return userService;
    }

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }
}
